package com.sh.data.engine.domain.shims.sql.select;

import com.sh.data.engine.domain.shims.sql.Context;
import com.sh.data.engine.domain.shims.sql.TerminalExpression;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class SelectSql implements TerminalExpression {

    private Context context;

    private boolean terminated = false;

    public SelectSql(Context context, String sql) {
        this.context = context;
        this.context.append(sql);
    }

    @Override
    public String toString() {
        return context.toString();
    }

    public Limit limit(int start, int size) {
        terminate();
        return new Limit(context, start, size);
    }

    public SelectSql addParameters(Object... values) {
        context.addParameters(values);
        return this;
    }

    @Override
    public <E> List<E> list(RowMapper<E> rowMapper) throws SQLException {
        return context.list(rowMapper);
    }

    @Override
    public ResultSet list() throws SQLException {
        return context.list();
    }

    @Override
    public <E> E single(RowMapper<E> rowMapper) throws SQLException {
        return context.single(rowMapper);
    }

    private void terminate() {
        if (!terminated) {
            final String newLine = System.getProperty("line.separator");
            this.context.appendWithSeparator(newLine);
            terminated = true;
        }
    }
}
